package pub.tbc.atps.initialize;

import com.google.common.collect.Ordering;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.atps.annotation.HandlerOrder;
import pub.tbc.atps.config.HandlerStore;
import pub.tbc.atps.config.PropConfig;
import pub.tbc.atps.process.Handler;
import pub.tbc.atps.process.executor.Executor;
import pub.tbc.toolkit.Objs;
import pub.tbc.toolkit.classes.ClassScanner;
import pub.tbc.toolkit.classes.impl.DefaultClassScanner;

import java.util.List;

/**
 * @author tbc on 2016/12/1 22:01.
 */
@Slf4j
public class HandlerInit {
    private static String basicPackage = PropConfig.get("basis-package");

    public static void handlerInit() {
        ClassScanner scanner = new DefaultClassScanner();
        List<Class<?>> classes = scanner.getClassListBySuper(basicPackage, Handler.class);

        classes.stream().sorted((c1, c2) -> {
            HandlerOrder order1 = c1.getAnnotation(HandlerOrder.class);
            HandlerOrder order2 = c2.getAnnotation(HandlerOrder.class);
            if (order1.value() > order2.value()) return 1;
            else if (order1.value() < order2.value()) return -1;
            else return 0;
        }).forEach(c -> {
            Handler handler = null;
            try {
                handler = (Handler) c.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("实例化Handler失败： {} ", e.getMessage());
                throw new RuntimeException(e.getMessage(), e);
            }
            if (Objs.nonEmpty(handler))
                HandlerStore.add(handler);

        });

        log.info("Handler loaded : {}", HandlerStore.getHandlers());
    }
}
